package leetcode.秋招.小红书;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/8/21 10:12
 * @description：
 */
public class 魔法师过河 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int[] path = new int[N];
        int count1 = 0;
        int count2 = 0;
        int min = Integer.MAX_VALUE;
        HashMap<Integer, int[]> map = new HashMap<>();
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < path.length; i++) {
            int num = in.nextInt();
            path[i] = num;
            if (num == 0) {
                list.add(i);
                map.put(i, new int[]{in.nextInt(), in.nextInt()});
            } else if (num == 1) {
                count1++;
            } else
                count2++;
        }
        if (Math.abs(count1 - count2) > list.size()) {
            System.out.println(-1);
            return;
        }
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{count1, count2, 0});
        for (int i = 0; i < list.size(); i++) {
            Integer key = list.get(i);
            int[] nums = map.get(key);
            int size = queue.size();
            while (size > 0) {
                int[] cur = queue.poll();
                if (Math.abs(cur[0] - cur[1]) > list.size() - i) break;
                if (cur[0] < cur[1] && nums[0] < nums[1]) {
                    queue.offer(new int[] {cur[0] + 1, cur[1], cur[2] + nums[0]});
                } else if (cur[0] > cur[1] && nums[0] > nums[1]) {
                    queue.offer(new int[] {cur[0], cur[1] + 1, cur[2] + nums[1]});
                } else {
                    queue.offer(new int[]{cur[0] + 1, cur[1], cur[2] + nums[0]});
                    queue.offer(new int[]{cur[0], cur[1] + 1, cur[2] + nums[1]});
                }
                size--;
            }
        }
        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            if (cur[0] == cur[1]) {
                min = Math.min(min, cur[2]);
            }
        }
        System.out.println(min);
    }

}
